// pages/expense-details/expense-details.js
Page({
  data: {
    patientInfo: {
      name: '',
      relation: '本人',
      idNumber: '',
      patientId: null
    },
    showPatientModal: false,
    patientList: [],
    expenseItems: [
      {
        id: 1,
        name: '硝酸甘油片',
        unitPrice: '25.00',
        quantity: 2,
        total: '50.00'
      },
      {
        id: 2,
        name: '美托洛尔片',
        unitPrice: '35.00',
        quantity: 3,
        total: '105.00'
      },
      {
        id: 3,
        name: '辛伐他汀片',
        unitPrice: '40.00',
        quantity: 2,
        total: '80.00'
      },
      {
        id: 4,
        name: '阿司匹林肠溶片',
        unitPrice: '30.00',
        quantity: 2,
        total: '60.00'
      }
    ],
    totalAmount: '295.00'
  },

  onLoad(options) {
    console.log('费用详情页面加载');
    
    // 加载当前就诊人信息
    this.loadCurrentPatient();
    
    // 接收传递的费用信息
    if (options.expense) {
      const expense = JSON.parse(options.expense);
      console.log('接收到的费用信息:', expense);
      
      // 根据不同的科室设置不同的费用明细
      this.setExpenseItemsByDepartment(expense.department);
    }
  },

  // 加载当前患者信息
  loadCurrentPatient() {
    // 从后端获取默认就诊人信息
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
            isDefault: p.isDefault === 1
          }))
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                patientId: defaultPatient.id
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                  patientId: firstPatient.id
                }
              })
            }
          }
        }
      }
    })
  },

  // 切换就诊人
  switchPatient() {
    // 先加载患者列表
    this.loadPatientList()
  },
  
  // 加载患者列表
  loadPatientList() {
    wx.showLoading({ title: '加载中...' })
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode === 200 && res.data) {
          let patientData = res.data
          
          // 处理数据格式
          if (typeof patientData === 'string') {
            try {
              patientData = JSON.parse(patientData)
            } catch (e) {
              console.error('JSON解析失败:', e)
              return
            }
          }
          
          // 处理Result包装的数据
          if (patientData.code !== undefined) {
            if (patientData.code !== 200) {
              console.error('后端返回错误:', patientData.message)
              wx.showToast({
                title: patientData.message || '请求失败',
                icon: 'none'
              })
              return
            }
            patientData = patientData.data
          }
          
          // 提取患者数组
          if (!Array.isArray(patientData)) {
            if (patientData.data && Array.isArray(patientData.data)) {
              patientData = patientData.data
            } else if (patientData.list && Array.isArray(patientData.list)) {
              patientData = patientData.list
            } else if (patientData.patients && Array.isArray(patientData.patients)) {
              patientData = patientData.patients
            } else {
              console.error('数据不是数组格式:', patientData)
              return
            }
          }
          
          // 构建选择列表
          const itemList = patientData.map(patient => 
            `${patient.name || patient.patientName} (${patient.relationTypeName || patient.relationship || '本人'})`
          )
          
          wx.showActionSheet({
            itemList: itemList,
            success: (res) => {
              if (res.tapIndex >= 0 && res.tapIndex < patientData.length) {
                const selectedPatient = patientData[res.tapIndex]
                const patientInfo = {
                  name: selectedPatient.name || selectedPatient.patientName,
                  relation: selectedPatient.relationTypeName || selectedPatient.relationship || '本人',
                  idNumber: selectedPatient.idCardNumber || selectedPatient.idCard || '622*********0909',
                  patientId: selectedPatient.id || selectedPatient.patientId
                }
                
                this.setData({
                  patientInfo: patientInfo
                })
                
                // 可选：缓存 patientId，便于后续页面使用
                const cacheUser = wx.getStorageSync('userInfo') || {}
                wx.setStorageSync('userInfo', { ...cacheUser, patientId: patientInfo.patientId })
                
                wx.showToast({
                  title: '已切换到' + patientInfo.name,
                  icon: 'success'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '加载患者列表失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        wx.hideLoading()
        console.error('网络请求失败:', error)
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        })
      }
    })
  },

  // 关闭就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 根据科室设置费用明细
  setExpenseItemsByDepartment(department) {
    const expenseItemsMap = {
      '心血管内科': [
        {
          id: 1,
          name: '硝酸甘油片',
          unitPrice: '25.00',
          quantity: 2,
          total: '50.00'
        },
        {
          id: 2,
          name: '美托洛尔片',
          unitPrice: '35.00',
          quantity: 3,
          total: '105.00'
        },
        {
          id: 3,
          name: '辛伐他汀片',
          unitPrice: '40.00',
          quantity: 2,
          total: '80.00'
        },
        {
          id: 4,
          name: '阿司匹林肠溶片',
          unitPrice: '30.00',
          quantity: 2,
          total: '60.00'
        }
      ],
      '内分泌科': [
        {
          id: 1,
          name: '二甲双胍片',
          unitPrice: '45.00',
          quantity: 2,
          total: '90.00'
        },
        {
          id: 2,
          name: '格列美脲片',
          unitPrice: '30.00',
          quantity: 3,
          total: '90.00'
        }
      ],
      '神经内科': [
        {
          id: 1,
          name: '卡马西平片',
          unitPrice: '80.00',
          quantity: 2,
          total: '160.00'
        },
        {
          id: 2,
          name: '苯妥英钠片',
          unitPrice: '40.00',
          quantity: 4,
          total: '160.00'
        }
      ],
      '消化内科': [
        {
          id: 1,
          name: '奥美拉唑胶囊',
          unitPrice: '60.00',
          quantity: 3,
          total: '180.00'
        },
        {
          id: 2,
          name: '雷贝拉唑片',
          unitPrice: '45.00',
          quantity: 6,
          total: '270.00'
        }
      ],
      '骨科': [
        {
          id: 1,
          name: '布洛芬缓释胶囊',
          unitPrice: '35.00',
          quantity: 4,
          total: '140.00'
        },
        {
          id: 2,
          name: '双氯芬酸钠片',
          unitPrice: '28.00',
          quantity: 5,
          total: '140.00'
        }
      ]
    };

    if (expenseItemsMap[department]) {
      const expenseItems = expenseItemsMap[department];
      // 计算合计金额
      const totalAmount = expenseItems.reduce((sum, item) => {
        return sum + parseFloat(item.total);
      }, 0);
      
      this.setData({
        expenseItems: expenseItems,
        totalAmount: totalAmount.toFixed(2)
      });
    }
  }
});
